package com.jinkaimen.kqb.ui.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;

import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.ChannelUtils;
import com.igexin.sdk.PushManager;
import com.jinkaimen.kqb.R;
import com.jinkaimen.kqb.application.AppApplication;
import com.jinkaimen.kqb.service.GetuiService;
import com.jinkaimen.kqb.service.PushService;
import com.jinkaimen.kqb.utils.PermissionUtils;
import com.umeng.analytics.MobclickAgent;


public class SplashActivity extends BaseActivity {

    public static final int MSG_WHAT_LAUNCHER_TIME_UP = 0;
    private static final int REQUEST_PERMISSION_SD_CAED_CODE = 1;

    //是否是第一次打开
    public static final String IS_FIRST_OPEN = "is_first_open_v0";
    private String picUrl;
    private String jumpUrl;
    private ImageView iconsplash;
    private Thread thread;
    private boolean isTure;


    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected boolean isFulleScreen() {
        return true;
    }

    @Override
    protected void initChannel() {
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "586c9a9e6e27a428320011de", ChannelUtils.getChannel()));
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected int initContentView() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initChildView() {
        iconsplash = (ImageView) findViewById(R.id.iconsplash);
        try {// TODO: 2017/6/29 友盟bug出现率比较高
            PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiService.class);
        Boolean isServiceRunningPush = false;
        //检查Service状态
        ActivityManager manager = (ActivityManager) AppApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.jinkaimen.addwallet.service.PushService".equals(service.service.getClassName())) {
                isServiceRunningPush = true;
            }
        }
        if (!isServiceRunningPush) {
            Intent i = new Intent(this, PushService.class);
            this.startService(i);
        }
    }

    @Override
    protected void initChildData() {

//        iconsplash.setImageResource(R.mipmap.iconsplash);

        boolean hasWriteSDCardPermission = PermissionUtils.hasWriteSDCardPermission();

        if (!hasWriteSDCardPermission) {


            showPopupWindow();
            return;
        } else {
            thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = MSG_WHAT_LAUNCHER_TIME_UP;
                    mHandler.sendMessage(msg);
                }
            });
            thread.start();
        }
    }

    @Override
    protected void setChildViewListener() {
        iconsplash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(jumpUrl)) {
                    isTure = true;
                    Bundle bundle = new Bundle();
                    bundle.putString(WebViewActivity.URL, jumpUrl);
                    ActivityUtils.startActivity(SplashActivity.this, WebViewActivity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case MSG_WHAT_LAUNCHER_TIME_UP:
//                if (SharedPreferencesUtils.getBool(IS_FIRST_OPEN, true)){
//                    ActivityUtils.startActivityAndFinishByAlpha(this, GuideActivity.class);
//                } else {
                if (!isTure) {
                    ActivityUtils.startActivityAndFinish(this, HomeActivity.class);
                }
//                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
////        这里做2秒的延时操作
//        isTure = false;
//        thread = new Thread(new Runnable() {
//            public void run() {
//                try {
//                    Thread.sleep(2000);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                Message msg = new Message();
//                msg.what = MSG_WHAT_LAUNCHER_TIME_UP;
//                mHandler.sendMessage(msg);
//            }
//        });
//        thread.start();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (requestCode == REQUEST_PERMISSION_SD_CAED_CODE) {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // contacts-related task you need to do.
                //        这里做2秒的延时操作
                thread = new Thread(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = MSG_WHAT_LAUNCHER_TIME_UP;
                        mHandler.sendMessage(msg);
                    }
                });
                thread.start();

            } else {
                ActivityUtils.finishActivityByAlpha(this);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void showPopupWindow() {

        final Dialog updateDialog = new Dialog(this, R.style.updateDialog);
        View view = View.inflate(this, R.layout.dialog_splash_per,
                null);

        Window window = updateDialog.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.6); // 改变的是dialog框在屏幕中的位置而不是大小
        p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
        updateDialog.setContentView(view);
        updateDialog.setCancelable(false);

        updateDialog.show();
        view.findViewById(R.id.btn_splash_act_dialog_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_SD_CAED_CODE);
            }
        });
    }

}
